"""
员工模型
"""
from datetime import datetime
from app import db


class Employee(db.Model):
    """员工表"""
    __tablename__ = 'mx_employees'
    
    id = db.Column(db.Integer, primary_key=True)
    employee_id = db.Column(db.String(50), unique=True, nullable=False, comment='工号')
    user_id = db.Column(db.Integer, nullable=True, comment='关联的系统账号ID')
    name = db.Column(db.String(100), nullable=False, comment='姓名')
    phone = db.Column(db.String(20), unique=True, comment='手机号')
    email = db.Column(db.String(100), comment='邮箱')
    company = db.Column(db.String(100), comment='所属子公司')
    department = db.Column(db.String(100), comment='部门')
    position = db.Column(db.String(100), comment='职位（岗位，用于审批流程）')
    project_id = db.Column(db.Integer, comment='当前参与的项目ID')
    status = db.Column(db.String(20), default='active', comment='状态: active, inactive')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联（使用 foreign_keys 显式指定，不在列定义中使用 ForeignKey）
    user_account = db.relationship('UserInfo', foreign_keys=[user_id], primaryjoin='Employee.user_id==UserInfo.id', backref='employee')
    
    def to_dict(self):
        return {
            'id': self.id,
            'employee_id': self.employee_id,
            'user_id': self.user_id,
            'name': self.name,
            'phone': self.phone,
            'email': self.email,
            'company': self.company,
            'department': self.department,
            'position': self.position,
            'project_id': self.project_id,
            'status': self.status,
            'has_account': self.user_id is not None,
            'account_name': self.user_account.account if self.user_account else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
